package com.synnex.wms.controller;
/**
 * 床位前后台交互
 * 
 * */

import com.synnex.wms.pojo.Chuangw;
import com.synnex.wms.service.ChuangwService;
import com.synnex.wms.service.FenleiService;
import com.synnex.wms.util.PageUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ChuangwController
 * */

@Controller
@RequestMapping(value = "/Chuangw")
public class ChuangwController {

	
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	
	@Autowired
	private ChuangwService ChuangwService;
	@Autowired
	private FenleiService FenleiService;
	
	 /*分页查询、模糊查询*/
	 @RequestMapping(value = "/page")
	 public void page(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageIndex = 1;//设置初始的当前页，页面显示的都是第一页
        int pageSize = 4;//设置每一页显示几条数据,用于计算总页数，此处设置的值必须与sql语句的limit最后的数值一样
        PageUtil<Chuangw> pageUtil = new PageUtil<Chuangw>();//初始化工具类
        List<Chuangw> list = new ArrayList<Chuangw>();
        if (request.getParameter("pageIndex") != null) {
            pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
        }//对页面上的分页标签传的值,进行获取,也是就点击'上一页或者下一页'传过来的pageindex
        pageUtil.setPageIndex(pageIndex);//保存至工具类
        
        String name = request.getParameter("name");
        Chuangw Chuangw = new Chuangw();
        Chuangw.setName(name);
        
        int number = ChuangwService.pagecount(Chuangw);//调用service层方法计算出总数据量，就是多少条数据.
        pageUtil.setPageNumber(number);//保存至工具类
        pageUtil.setPageSize(pageSize);//保存至工具类
        pageUtil.setPageCount((int) Math.ceil((double) (pageUtil
                .getPageNumber() / pageUtil.getPageSize())) + 1);//计算出总页数,并封装到工具类
        int index = (pageIndex - 1) * pageSize;//计算出每一页从数据库中第几条数据开始取值，也就是limit后面的第一个数字
        Chuangw.setFenye(index);
        list = ChuangwService.showlist(Chuangw);//调用service层的方法，取得数据库中的值
        pageUtil.setList(list);//保存到工具类中的集合
        request.setAttribute("pageUtil", pageUtil);//传递到页面，存入值栈中
		request.getRequestDispatcher("/jsp/Chuangw/list.jsp").forward(request,
				response);
	}
	 /*分页查询、模糊查询*/
	 @RequestMapping(value = "/page2")
	 public void page2(HttpServletRequest request, HttpServletResponse response)
			 throws ServletException, IOException {
		 int pageIndex = 1;//设置初始的当前页，页面显示的都是第一页
		 int pageSize = 4;//设置每一页显示几条数据,用于计算总页数，此处设置的值必须与sql语句的limit最后的数值一样
		 PageUtil<Chuangw> pageUtil = new PageUtil<Chuangw>();//初始化工具类
		 List<Chuangw> list = new ArrayList<Chuangw>();
		 if (request.getParameter("pageIndex") != null) {
			 pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
		 }//对页面上的分页标签传的值,进行获取,也是就点击'上一页或者下一页'传过来的pageindex
		 pageUtil.setPageIndex(pageIndex);//保存至工具类
		 
		 String name = request.getParameter("name");
		 Chuangw Chuangw = new Chuangw();
		 Chuangw.setName(name);
		 
		 int number = ChuangwService.pagecount(Chuangw);//调用service层方法计算出总数据量，就是多少条数据.
		 pageUtil.setPageNumber(number);//保存至工具类
		 pageUtil.setPageSize(pageSize);//保存至工具类
		 pageUtil.setPageCount((int) Math.ceil((double) (pageUtil
				 .getPageNumber() / pageUtil.getPageSize())) + 1);//计算出总页数,并封装到工具类
		 int index = (pageIndex - 1) * pageSize;//计算出每一页从数据库中第几条数据开始取值，也就是limit后面的第一个数字
		 Chuangw.setFenye(index);
		 list = ChuangwService.showlist(Chuangw);//调用service层的方法，取得数据库中的值
		 pageUtil.setList(list);//保存到工具类中的集合
		 request.setAttribute("pageUtil", pageUtil);//传递到页面，存入值栈中
		 request.getRequestDispatcher("/jsp/Chuangw/list2.jsp").forward(request,
				 response);
	 }
	 
	
	
	/*删除数据*/
	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable Integer id) {
		ChuangwService.deleteByPrimaryKey(id);
		return "redirect:/Chuangw/page";
	
	}
	
	/*添加、插入数据*/
	@RequestMapping(value = "/insert")
	public String insertTp(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Chuangw Chuangw=new Chuangw();
	   	 FileItemFactory itemFactory=new DiskFileItemFactory();
	   	 ServletFileUpload fileUpload=new ServletFileUpload(itemFactory);
	   	 try {
				List<FileItem> items=fileUpload.parseRequest(request);
				for(FileItem fileItem:items){
					//判断是否是普通表单数据
					if(fileItem.isFormField()){//是普通表单
						//获取表单名称
						if("name".equals(fileItem.getFieldName())){
							Chuangw.setName(fileItem.getString("utf-8"));
						}else if("introduce".equals(fileItem.getFieldName())){
							Chuangw.setIntroduce(fileItem.getString("utf-8"));
						}else if("number".equals(fileItem.getFieldName())){
							if(!"".equals(fileItem.getString())&&fileItem.getString()!=null)
							Chuangw.setNumber(Integer.parseInt(fileItem.getString("utf-8")));
						}else if("state".equals(fileItem.getFieldName())){
							if(!"".equals(fileItem.getString())&&fileItem.getString()!=null)
							Chuangw.setState(Integer.parseInt(fileItem.getString()));
						}
					}else{//文件
						if("picture".equals(fileItem.getFieldName())){
							//获取上传的文件类型
							fileItem.getContentType();
							//获取上传的文件的大小
							fileItem.getSize();
							
							//获取文件名称
							String oldName=fileItem.getName();
							if(!"".equals(oldName)&&oldName!=null){
								//获取文件的后缀
								String type=oldName.substring(oldName.lastIndexOf("."));
								//创建新名称
								String newName=System.currentTimeMillis()+type;
								Chuangw.setPicture(newName);

								
								//上传的路径
								String uploadPath=request.getRealPath("/upload");
								System.out.println("uploadPath:"+uploadPath);
								File parentFile=new File(uploadPath);
								//判断文件是否存在
								if(!parentFile.exists()){
									parentFile.mkdirs();
								}
								File file=new File(parentFile, newName);
								//上传文件
								fileItem.write(file);
							}else{
								//查询原来的图片名称及路径
								
							}
							
						}
					}
				}
				
				Date currentTime = new Date();
				String csrq = formatter.format(currentTime);
				
				Chuangw.setEnddate(formatter.parse(csrq));
				int num=ChuangwService.insert(Chuangw);
				if(num>0){
					//重定向
					return "redirect:/Chuangw/page";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	   	 	return null;
	}
	
	
	/*修改数据前，根据id查询数据*/
	@RequestMapping("/toUpdateLocPage/{id}")
	public void toUpdateLocPage(@PathVariable("id") Integer id,
			HttpServletResponse response, HttpServletRequest request)
			throws ServletException, IOException {
		
		Chuangw Chuangw = ChuangwService.selectByPrimaryKey(id);
		request.setAttribute("Chuangw", Chuangw);
		request.getRequestDispatcher("/jsp/Chuangw/update.jsp").forward(request,
				response);

	}
	
	/*修改*/
	@RequestMapping(value = "/update")
	public String update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	 Chuangw Chuangw=new Chuangw();
   	 FileItemFactory itemFactory=new DiskFileItemFactory();
   	 ServletFileUpload fileUpload=new ServletFileUpload(itemFactory);
   	 try {
			List<FileItem> items=fileUpload.parseRequest(request);
			for(FileItem fileItem:items){
				//判断是否是普通表单数据
				if(fileItem.isFormField()){//是普通表单
					//获取表单名称
					if("name".equals(fileItem.getFieldName())){
						Chuangw.setName(fileItem.getString("utf-8"));
					}else if("introduce".equals(fileItem.getFieldName())){
						Chuangw.setIntroduce(fileItem.getString("utf-8"));
					}else if("number".equals(fileItem.getFieldName())){
						if(!"".equals(fileItem.getString())&&fileItem.getString()!=null)
						Chuangw.setNumber(Integer.parseInt(fileItem.getString("utf-8")));
					}else if("state".equals(fileItem.getFieldName())){
						if(!"".equals(fileItem.getString())&&fileItem.getString()!=null)
						Chuangw.setState(Integer.parseInt(fileItem.getString()));
					}else if("id".equals(fileItem.getFieldName())){
						if(!"".equals(fileItem.getString())&&fileItem.getString()!=null)
						Chuangw.setId(Integer.parseInt(fileItem.getString()));
					}
				}else{//文件
					if("picture".equals(fileItem.getFieldName())){
						//获取上传的文件类型
						fileItem.getContentType();
						//获取上传的文件的大小
						fileItem.getSize();
						
						//获取文件名称
						String oldName=fileItem.getName();
						if(!"".equals(oldName)&&oldName!=null){
							//获取文件的后缀
							String type=oldName.substring(oldName.lastIndexOf("."));
							//创建新名称
							String newName=System.currentTimeMillis()+type;
							Chuangw.setPicture(newName);

							
							//上传的路径
							String uploadPath=request.getRealPath("/upload");
							System.out.println("uploadPath:"+uploadPath);
							File parentFile=new File(uploadPath);
							//判断文件是否存在
							if(!parentFile.exists()){
								parentFile.mkdirs();
							}
							File file=new File(parentFile, newName);
							//上传文件
							fileItem.write(file);
						}else{
							//查询原来的图片名称及路径
							
						}
						
					}
				}
			}
			Date currentTime = new Date();
			String csrq = formatter.format(currentTime);
			
			Chuangw.setEnddate(formatter.parse(csrq));		
			int num=ChuangwService.updateByPrimaryKeySelective(Chuangw);
			if(num>0){
				//重定向
				return "redirect:/Chuangw/page";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
   	 	return null;
	}
	
	
	/*床位 预约占用*/
	@RequestMapping("/yuyue/{id}")
	public String chuku(@PathVariable("id") Integer id,
			HttpServletResponse response, HttpServletRequest request)
			throws ServletException, IOException {
		
		Chuangw Chuangw = ChuangwService.selectByPrimaryKey(id);
		Chuangw.setState(1);
		ChuangwService.updateByPrimaryKeySelective(Chuangw);
		
		return "redirect:/Chuangw/page2";

	}
	
	
}